<?php

namespace app\common\repositories\bill;

use think\facade\Db;
use app\common\dao\bill\BillLogDao;
use app\common\repositories\BaseRepository;
/**
 * Class BillLogRepository
 *
 * @mixin BillLogDao
 */
class BillLogRepository extends BaseRepository
{

    public function __construct(BillLogDao $dao)
    {
        $this->dao = $dao;
    }

    public function getList(array $where, $page, $limit)
    {
        $query = $this->dao->search($where);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->with([
                'userInfo' => function ($query) {
                    $query->field('id,username');
                    $query->bind(['username' => 'username']);
                }
            ])
            ->order('id', 'desc')
            ->select();
        return compact('list', 'count');
    }

    public function addInfo(int $billId, int $userId, $remark = null, $catalogId = null)
    {
        $data['user_id'] = $userId;
        $data['bill_id'] = $billId;
        if (isset($remark)) {
            $data['remark'] = $remark;
        }
        if (isset($catalogId)) {
            $data['catalog_id'] = $catalogId;
        }
        $data['track_ip'] = app('request')->ip();
        $this->dao->create($data);
    }

    public function getInfo($data)
    {
        return $this->dao->getSearch($data)->find();
    }

    public function editInfo($id, array $data)
    {
        return Db::transaction(function () use ($data, $id) {
            $res = $this->dao->update($id, $data);
            return ($res);
        });
    }

    public function batchDelete(array $ids, int $userId = 0)
    {
        $list = $this->dao->selectWhere([
            ['id', 'in', $ids]
        ]);
        if ($list) {
            foreach ($list as $k => $v) {
                $this->deleteInfo($v, $userId);
            }
            return $list;
        }
        return [];
    }

    public function deleteInfo($info, int $userId = 0)
    {
        $this->dao->delete($info['id']);
    }
}
